/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.mapreduce;

import java.util.List;
import java.util.ArrayList;
import org.sss.util.Factory;

import org.sss.mapreduce.datatype.Packable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Encodings {
  @SuppressWarnings("unused")
  private static Logger logger = LoggerFactory.getLogger(Encodings.class);
  private List<Encoding> encodings;

  public Encodings() {
    this(null);
  }

  public Encodings(ClassLoader cl) {
    this.encodings = new ArrayList<Encoding>();
    this.encodings.add(BasicTypeEncoding.getInstance());
    this.encodings.add(SelfEncoding.getInstance());
    this.encodings.add(new MessagePackEncoding(cl));
  }

  public synchronized boolean canEncode(Class<? extends Packable> klass) throws SssException
  {
    for (Encoding e: encodings) {
      if (e.canEncode(klass)) {
        return true;
      }
    }
    return false;
  }

  public synchronized Decoder createDecoder(Class<? extends Packable> klass) throws SssException {
    for (Encoding e: encodings) {
      if (e.canEncode(klass)) {
        return e.createDecoder(klass);
      }
    }
    throw new SssException("Can't get decoder for " + klass.getName());
  }

  public synchronized Encoder createEncoder(Class<? extends Packable> klass) throws SssException {
    for (Encoding e: encodings) {
      if (e.canEncode(klass)) {
        return e.createEncoder(klass);
      }
    }
    throw new SssException("Can't get encoder for " + klass.getName());
  }

  public synchronized Factory<Encoder> getEncoderFactory(final Class<? extends Packable> klass) {
    return new Factory<Encoder>() {
      public Encoder create() {
        try {
          return createEncoder(klass);
        } catch (SssException e) {
          throw new RuntimeException(e);
        }
      }
    };
  }

  public synchronized Factory<Decoder> getDecoderFactory(final Class<? extends Packable> klass) {
    return new Factory<Decoder>() {
      public Decoder create() {
        try {
          return createDecoder(klass);
        } catch (SssException e) {
          throw new RuntimeException(e);
        }
      }
    };
  }
}
